import html2Canvas from "html2canvas";
import jsPDF from "jspdf";

async function drawPdf(dom, pdf, option = { width: 210, height: 297 }) {
  const element = dom || document.getElementById("myCanvas");
  window.scrollTo(0, 0);

  const canvas = await html2Canvas(element, {
    useCORS: true,
    allowTaint: true,
    scale: 1.5,
    logging: false,
    windowWidth: element.scrollWidth,
    windowHeight: element.scrollHeight,
    x: 0,
    y: 0
  });

  const contentWidth = canvas.width;
  const contentHeight = canvas.height;

  const pageRatio = option.width / option.height;
  const contentRatio = contentWidth / contentHeight;

  let pdfWidth = option.width;
  let pdfHeight;

  if (contentRatio > pageRatio) {
    pdfWidth = option.width;
    pdfHeight = (contentHeight * pdfWidth) / contentWidth;
  } else {
    pdfHeight = option.height;
    pdfWidth = (contentWidth * pdfHeight) / contentHeight;
  }

  const xOffset = (option.width - pdfWidth) / 2;

  const pageData = canvas.toDataURL("image/jpeg", 1.0);
  pdf = pdf || new jsPDF({
    orientation: contentWidth > contentHeight ? "l" : "p",
    unit: "mm",
    format: [option.width, option.height]
  });

  pdf.addImage(
    pageData,
    "JPEG",
    xOffset,
    0,
    pdfWidth,
    pdfHeight,
    null,
    'FAST'
  );

  return pdf;
}

function handlePrint(url) {
  const printWindow = window.open(url);
  printWindow.onload = function () {
    const style = `
      @media print {
        @page {
          size: auto;
          margin: 0;
        }
        body {
          transform: scale(1);
          transform-origin: top left;
          width: 100%;
          height: 100%;
          overflow: hidden;
        }
        img {
          width: 100%;
          height: auto;
        }
      }
    `;
    const styleSheet = printWindow.document.createElement("style");
    styleSheet.type = "text/css";
    styleSheet.innerText = style;
    printWindow.document.head.appendChild(styleSheet);
    printWindow.print();
    printWindow.onafterprint = function () {
      printWindow.close();
      URL.revokeObjectURL(url); // 清理资源
    };
  };
}

const htmlToPdf = {
  async exportPdf(dom, name, option) {
    try {
      let pdf = null;
      if (dom instanceof Array) {
        for (let index = 0; index < dom.length; index++) {
          pdf = await drawPdf(dom[index], pdf, option);
          if (index < dom.length - 1) {
            pdf.addPage();
          }
        }
      } else {
        pdf = await drawPdf(dom, pdf, option)
      }
      pdf.save(`${name}.pdf`);
    } catch (error) {
      console.error("导出PDF失败", error);
    }
  },

  async printPdf(dom, option) {
    try {
      let pdf = null;
      if (dom instanceof Array) {
        for (let index = 0; index < dom.length; index++) {
          pdf = await drawPdf(dom[index], pdf, option);
          if (index < dom.length - 1) {
            pdf.addPage();
          }
        }
      } else {
        pdf = await drawPdf(dom, pdf, option)
      }
      const pdfBlob = pdf.output('blob');
      const url = URL.createObjectURL(pdfBlob);
      handlePrint(url);
    } catch (error) {
      console.error("打印PDF失败", error);
    }
  },
};

export default htmlToPdf;
